package filescan

import (
	"os"
	"path"
	"strings"
)

// 文件单元
type Myfile struct {
	Name        string `json:"name"`
	Mftype      string `json:"type"`
	Realpath    string `json:"realpath"`
	KidNode     map[string]*Myfile
	KidDirCount int    `json:"-"`
	RootDir     string `json:"-"`
}

// 文件输出
type FileMap struct {
	Path  string `json:"path"`
	Ftype string `json:"type"`
}

// 用于过滤文件类型
type FileTypeList struct {
	ChosenType []string
}

func (ft *FileTypeList) String() string {

	return strings.Join(ft.ChosenType, ",")

}
func (ft *FileTypeList) Set(value string) error {
	ft.ChosenType = strings.Split(value, ",")
	return nil
}

// 新建根节点
func New(root string) Myfile {
	return Myfile{
		Name:     root,
		Mftype:   "Dir",
		Realpath: root,
		RootDir:  root,
		KidNode:  make(map[string]*Myfile, 1000),
	}
}

type Filechane chan Myfile

var Count int
var LongCount int

func init() {
	Count = 0
	LongCount = 0

}

func Scan(mf *Myfile) {
	files, err := os.ReadDir(mf.Realpath)
	if err != nil {
		panic(err)
	}

	for _, file := range files {

		x := file.IsDir()
		tmp := Myfile{
			Name:     file.Name(),
			Mftype:   path.Ext(file.Name()),
			Realpath: mf.Realpath + "/" + file.Name(),
		}

		//		println(tmp.Realpath)
		if x {
			tmp.Mftype = "Dir"
			mf.KidDirCount++
			tmp.KidNode = make(map[string]*Myfile, 100)
		}
		switch tmp.Mftype {
		case ".jpg", ".JPG", ".png", ".gif", ".jpeg", ".bmp", ".svg", ".webp":
			tmp.Mftype = "Image"

		case ".mp4", ".avi", ".flv", ".wmv", ".mov", ".mkv", ".rmvb", ".3gp", ".webm":
			tmp.Mftype = "Video"

		case ".mp3", ".wav", ".flac", ".aac", ".m4a", ".ape", ".wma":
			tmp.Mftype = "Audio"

		case ".html", ".htm":
			tmp.Mftype = "Html"

		}

		mf.KidNode[tmp.Realpath] = &tmp

	}

}

func Field(mf *Myfile, fmp []FileMap, lenth int, typelist string, rootpath string) int {
	for _, file := range mf.KidNode {
		file.Realpath = file.Realpath[len(rootpath):]
		switch file.Mftype {
		case "Dir":
			Field(file, fmp, lenth, typelist, rootpath)
		case typelist:
			LenthFun(lenth, fmp, file)
		default:
			{
				if typelist == "" {
					LenthFun(lenth, fmp, file)
				}
				continue
			}
		}
	}

	if LongCount != 0 {
		return LongCount
	} else {
		return Count
	}
}

// 防止超出初始大小无法处理
func LenthFun(lenth int, fmp []FileMap, file *Myfile) {
	if Count < lenth {
		fmp[Count] = FileMap{
			Path:  file.Realpath,
			Ftype: file.Mftype,
		}
		Count++
	} else if Count > lenth {
		fmp = append(fmp, FileMap{
			Path:  file.Realpath,
			Ftype: file.Mftype,
		})
		LongCount++
	} else if Count == lenth {
		fmp = append(fmp, FileMap{
			Path:  file.Realpath,
			Ftype: file.Mftype,
		})
		LongCount = Count
	}

}
